package com.example.verifysdk.compare;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.view.View;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.example.verifysdk.LogUtil;
import com.example.verifysdk.R;
import com.example.verifysdk.ResponseException;
import com.example.verifysdk.SpHelper;
import com.example.verifysdk.UploadHelper;
import com.example.verifysdk.camera.CameraActivity;
import com.example.verifysdk.camera.FileUtil;
import com.example.verifysdk.creatcode.CreatCodePresenter;
import com.example.verifysdk.creatcode.CreatCodePresenter.CreatCodeView;
import com.example.verifysdk.creatcode.LoginObjBean;
import com.example.verifysdk.easypermissions.EasyPermissions;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.app.ProgressDialog.STYLE_SPINNER;

/**
 * LiuV
 * 上传个人和身份证照片比对页面
 */
public class CompareActivity extends Activity implements
        View.OnClickListener, EasyPermissions.PermissionCallbacks, ComparePresenter.CompareView, CreatCodeView {
    private static final String TAG = CompareActivity.class.getSimpleName();

    private static final String[] sPermissionArray = {
            Manifest.permission.CAMERA,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };
    private static final int MY_CAMERA_READ_WRITE = 79;
    private static final int FROM_STORE = 22;
    private static final int FROM_CAMERA = 33;
    private static final int IMG_VIEW_HEADER = 1;
    private static final int IMG_VIEW_ID_CARD = 2;

    private static final String IMG_TYPE_HEAD = "1";
    private static final String IMG_TYPE_IDENTITY = "2";

    private static final int REGIST_FAILED_DEFAULT = 0;
    private static final int REGIST_SUCCESS = 1;    //验证提交成功
    private static final int REGIST_FAILED_IS_REGISTERED = 2;   //已经验证并提交过,禁止重复验证
    private static final int REGIST_FAILED_CANCEL = 3;  //用户点击了取消,验证提交失败
    private static final int REGIST_FAILED_PARAMS_ERROR = 4;    //APP传入SDK的参数错误,验证提交失败
    private static final int REGIST_FAILED_IS_REGISTERED_UPLOAD_IMG_FAIL = 5;   //人脸验证成功,提交照片失败,可以生成二维码,但是不能显示照片

    private ImageView mBackIv;
    private ImageView mFirIv;
    private ImageView mSecIv;
    private TextView mNameEt;
    private TextView mIdentityEt;
    private EditText mPhoneEt;
    private LinearLayout mPersonInfoLl;
    private Button mStartCompareBtn;

    private AlertDialog mAlertDialog;
    private ProgressDialog mProgressDialog;

    private String mPic1stPath;
    private String mPic2ndPath;

    private int mWhichPic;

    private String mName = "";
    private String mIdentity = "";
    private String mPhone;
    private String mAppPartner;    //合作伙伴id
    private String mAppPartnerRemark;  //合作伙伴內部用戶id
    private String mTotp;
    private boolean mReturnId;
    private boolean mHasFace = true;

    private ComparePresenter mComparePresenter;
    private CreatCodePresenter mCreatCodePresenter;
    private SpHelper mSpHelper;
    private Bundle mBundle;
    private Intent mIntent;
    private boolean mUserNotRegistered = true;

    private long mTakePhotoTime;
    private CompareHandler mHandler = new CompareHandler();

    protected class CompareHandler extends Handler{
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            LogUtil.i(TAG, "---handleMessage==msg.what==" + msg.what);
            switch (msg.what){
                case 1:
                    //处理图片时拿到的图片是空的
                    break;
                case 2:
                    //图片经过压缩--旋转--裁剪等环节，并且已经保存在了本地文件
                    setImageViewUri((String) msg.obj);
//                    updateMsgProgressBar(getString(R.string.checking_face_tip));
                    dismissProgressBar();
                    LogUtil.i(TAG, "---image.size.after===" + (new File(mPic1stPath).length()));
                    break;
                case 3:
                    dismissProgressBar();
                    mHasFace = true;
                    break;
                case 4:
                    mHasFace = false;
                    dismissProgressBar();
                    showToast(getString(R.string.not_has_face_tip), 1);
                    break;
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        setContentView(R.layout.compare_activity);
        initView();
        initData();
    }

    protected void initView() {
        mBackIv = findViewById(R.id.top_bar_back_iv);
        mFirIv = findViewById(R.id.compare_header_iv);
        mSecIv = findViewById(R.id.compare_id_card_iv);
        mNameEt = findViewById(R.id.compare_name_et);
        mIdentityEt = findViewById(R.id.compare_identity_code_et);
        mPhoneEt = findViewById(R.id.compare_phone_et);
        mStartCompareBtn = findViewById(R.id.compare_to_do_btn);
        mPersonInfoLl = findViewById(R.id.compare_person_info_ll);

        mBackIv.setOnClickListener(this);
        mFirIv.setOnClickListener(this);
        mSecIv.setOnClickListener(this);
        mStartCompareBtn.setOnClickListener(this);

        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setProgressStyle(STYLE_SPINNER);
        mProgressDialog.setCancelable(false);
    }

    protected void initData() {
        mIntent = getIntent();
        mBundle = mIntent.getExtras();
        mComparePresenter = new ComparePresenter();
        mComparePresenter.setmCompareView(this);

        mCreatCodePresenter = new CreatCodePresenter();
        mCreatCodePresenter.setmCreatCodeView(this);

        if (mBundle != null) {
            mAppPartner = mBundle.getString("partnerId");
            mAppPartnerRemark = mBundle.getString("userId");
            mTotp = mBundle.getString("totp");
            mPhone = mBundle.getString("phone");
        }

        if (TextUtils.isEmpty(mAppPartner) || TextUtils.isEmpty(mAppPartnerRemark)) {
            showToast(getString(R.string.params_error), 0);
            setResultAndFinish(REGIST_FAILED_PARAMS_ERROR);
        }

        mSpHelper = new SpHelper(this);
        mSpHelper.putPartenrRemark(mAppPartnerRemark);

        if (TextUtils.isEmpty(mTotp)) {
            mTotp = "000000";
        }
        if (!TextUtils.isEmpty(mPhone)) {
            mPhoneEt.setText(mPhone);
        }
        //如若不重新验证，则登录验证状态
        if (!mTotp.equals("retry")) {
            mCreatCodePresenter.login(mAppPartner, mAppPartnerRemark, mTotp);
        }
    }

    public static void startCompare(Activity activity, String partnerId, String userId){
        Bundle bundle = new Bundle();
        bundle.putString("partnerId", partnerId);
        bundle.putString("userId", userId);
        Intent intent = new Intent(activity, CompareActivity.class);
        intent.putExtras(bundle);
        activity.startActivityForResult(intent, 666);
    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.top_bar_back_iv) {
            backPressed();
        } else if (i == R.id.compare_header_iv) {
            mWhichPic = IMG_VIEW_HEADER;
            checkSalfPermissionOrDoNext(FROM_CAMERA);
            mStartCompareBtn.setText(getString(R.string.start_verify));
        } else if (i == R.id.compare_id_card_iv) {
            mWhichPic = IMG_VIEW_ID_CARD;
            checkSalfPermissionOrDoNext(FROM_CAMERA);
            mStartCompareBtn.setText(getString(R.string.start_verify));
        } else if (i == R.id.compare_to_do_btn) {
            startCompare();
        } else if (i == R.id.compare_dialog_from_camare_tv) {
            checkSalfPermissionOrDoNext(FROM_CAMERA);
            if (mAlertDialog != null && mAlertDialog.isShowing()) {
                mAlertDialog.dismiss();
            }
        } else if (i == R.id.compare_dialog_from_store_tv) {
            checkSalfPermissionOrDoNext(FROM_STORE);
            if (mAlertDialog != null && mAlertDialog.isShowing()) {
                mAlertDialog.dismiss();
            }
        }
    }

    private void backPressed(){
        if (!TextUtils.isEmpty(mSpHelper.getSdkToken())){
            setResultAndFinish(REGIST_FAILED_IS_REGISTERED_UPLOAD_IMG_FAIL);
        }else {
            setResultAndFinish(REGIST_FAILED_CANCEL);
        }
    }

    private void showChooseDialog() {
        if (mAlertDialog == null) {
            mAlertDialog = new AlertDialog.Builder(this).create();
        }
        mAlertDialog.setCancelable(true);
        mAlertDialog.show();
        Window window = mAlertDialog.getWindow();
        window.setContentView(R.layout.choose_image_dialog);
        TextView cameraTv = window.findViewById(R.id.compare_dialog_from_camare_tv);
        TextView storeTv = window.findViewById(R.id.compare_dialog_from_store_tv);

        cameraTv.setOnClickListener(this);
        storeTv.setOnClickListener(this);
    }

    private void selectImageFromCamare() {
        mTakePhotoTime = System.currentTimeMillis();
        File cameraSaveFile = UploadHelper.getCameraSaveFile(this, mTakePhotoTime);
        if (cameraSaveFile != null) {
            if (mWhichPic == IMG_VIEW_HEADER){
                UploadHelper.selectImageFromCamer(this, UploadHelper.REQUEST_CODE_TAKE_PICTURE, cameraSaveFile);
            }else {
                Intent intent = new Intent(this, CameraActivity.class);
                intent.putExtra(CameraActivity.KEY_OUTPUT_FILE_PATH,
                        FileUtil.getSaveFile(getApplication()).getAbsolutePath());
                intent.putExtra(CameraActivity.KEY_CONTENT_TYPE, CameraActivity.CONTENT_TYPE_ID_CARD_FRONT);
                startActivityForResult(intent, UploadHelper.REQUEST_CODE_TAKE_PICTURE);
            }
        } else {
            showToast(getString(R.string.please_check_SDcard), Toast.LENGTH_SHORT);
        }
    }

    private void selectImageFromStore() {
        UploadHelper.selectImageFromStore(this, UploadHelper.REQUEST_CODE_SELECT_ALBUM);
    }

    //放入需要先得到权限的方法，根据requestCode值调用
    private void doNextAction(int whichAction) {
        switch (whichAction) {
            case FROM_STORE:
                selectImageFromStore();
                break;
            case FROM_CAMERA:
                selectImageFromCamare();
                break;
            default:
        }
    }

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        LogUtil.i(TAG, "---onTrimMemory===" + level);
    }

    private void setResultAndFinish(int registResult) {
        mIntent.putExtra("identity", registResult == REGIST_SUCCESS && mReturnId ? mIdentity : "");
        setResult(registResult, mIntent);
        finish();
    }

    @Override
    public void onBackPressed() {
        backPressed();
    }

    /**
     * 权限相关
     * @param whichAction
     */
    private void checkSalfPermissionOrDoNext(int whichAction) {
        //是否拥有危险权限
        if (EasyPermissions.hasPermissions(this, sPermissionArray)) {
            doNextAction(whichAction);
        } else {
            ActivityCompat.requestPermissions(this, sPermissionArray, whichAction);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(
                requestCode,
                permissions,
                grantResults,
                this);
    }

    /**
     * 申请权限结果
     * @param requestCode
     * @param perms
     */
    @Override
    public void onPermissionsGranted(int requestCode, List<String> perms) {
        doNextAction(requestCode);
    }

    @Override
    public void onPermissionsDenied(int requestCode, List<String> perms) {
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Activity.RESULT_OK) {
            String path = "";
            switch (requestCode) {
                case UploadHelper.REQUEST_CODE_TAKE_PICTURE:
                    if (mWhichPic == IMG_VIEW_HEADER){
                        updateMsgProgressBar(getString(R.string.processing_image_tip));
                        path = UploadHelper.getCameraSaveFile(this, mTakePhotoTime).getPath();
                        LogUtil.i(TAG, "---image.file===" + path);
                        LogUtil.i(TAG, "---image.size.before===" + (new File(path).length()));
                        processImage(path);
                    }else {
                        path = FileUtil.getSaveFile(getApplicationContext()).getAbsolutePath();
                        setImageViewUri(path);
                    }
                    break;
                case UploadHelper.REQUEST_CODE_SELECT_ALBUM:
                    path = UploadHelper.getImageAbsolutePath(this, data.getData());
                    setImageViewUri(path);
                    break;
                default:
            }
        }
    }

    private void processImage(String path){
        //压缩图片，让图片小于1000Kb
        UploadHelper.compressImageFile(path, 1000, mHandler);

    }

    private void setImageViewUri(String path) {
        switch (mWhichPic) {
            case IMG_VIEW_HEADER:
                mPic1stPath = path;
                LogUtil.i(TAG, "---IMG_VIEW_HEADER===" + path);
                mFirIv.setBackgroundResource(TextUtils.isEmpty(mPic1stPath) ? R.mipmap.bg_upload_person : 0);
                Glide.with(this).load(path)
                        .apply(new RequestOptions().skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE))
                        .into(mFirIv);
                break;
            case IMG_VIEW_ID_CARD:
                mPic2ndPath = path;
//                LogUtil.i(TAG, "---IMG_VIEW_ID_CARD===" + path);
                mSecIv.setBackgroundResource(TextUtils.isEmpty(mPic2ndPath) ? R.mipmap.bg_upload_idcard : 0);
                Glide.with(this).load(path)
                        .apply(new RequestOptions().skipMemoryCache(true).diskCacheStrategy(DiskCacheStrategy.NONE))
                        .into(mSecIv);
                break;
            default:
        }
    }

    /**
     * 开始验证
     */
    private void startCompare() {
        if (TextUtils.isEmpty(mPic1stPath)) {
            showToast(getString(R.string.please_choose_1st_img), Toast.LENGTH_LONG);
            return;
        }
        if (TextUtils.isEmpty(mPic2ndPath)) {
            showToast(getString(R.string.please_choose_2nd_img), Toast.LENGTH_LONG);
            return;
        }
        if (!mHasFace){
            showToast(getString(R.string.not_has_face_tip), Toast.LENGTH_LONG);
            return;
        }
        mPhone = mPhoneEt.getText().toString().trim();
        if (TextUtils.isEmpty(mPhone)) {
//            return;
            mPhone = "";
        }
        if (mStartCompareBtn.getText().equals("确认")) {
            if (TextUtils.isEmpty(mNameEt.getText().toString().trim()) ||
                    TextUtils.isEmpty(mIdentityEt.getText().toString().trim())){
                showToast(getString(R.string.discern_fail), Toast.LENGTH_LONG);
                return;
            }
            mComparePresenter.infoIsOk();
        }else {
            startUploadAllImg();
        }
    }

    private void dismissProgressBar() {
        if (mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }

    private void updateMsgProgressBar(final String msg) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                if (!mProgressDialog.isShowing()) {
                    mProgressDialog.show();
                }
                mProgressDialog.setMessage(msg);
            }
        });
    }

    private void showToast(final String toast, final int showMode) {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                Toast.makeText(CompareActivity.this, toast, showMode).show();
            }
        });
    }

    private void startUploadAllImg() {
        File pic1stFile = new File(mPic1stPath);
        File pic2ndFile = new File(mPic2ndPath);
        LogUtil.i(TAG, "---startUploadAllImg=pic1stFile.length==" + pic1stFile.length());
        LogUtil.i(TAG, "---startUploadAllImg=pic2ndFile.length==" + pic2ndFile.length());
        Map<File, String> imgFileMap = new HashMap<File, String>();
        imgFileMap.put(pic1stFile, IMG_TYPE_HEAD);
        imgFileMap.put(pic2ndFile, IMG_TYPE_IDENTITY);
        mComparePresenter.uploadIdAndAllImg(mAppPartner, mAppPartnerRemark, imgFileMap);
        updateMsgProgressBar(getString(R.string.be_uploading));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mProgressDialog.dismiss();
    }

    @Override
    public void uploadAllImgSuccess(final String name, final String id, boolean returnId) {
        mName = name;
        mIdentity = id;
        mReturnId = returnId;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mPersonInfoLl.setVisibility(View.VISIBLE);
                mNameEt.setText(name);
                mIdentityEt.setText(id);
                mStartCompareBtn.setText("确认");
                dismissProgressBar();
            }
        });
        showToast("请确认信息是否正确，正确点击确认按钮", 0);
        System.gc();

    }

    @Override
    public void uploadImgFail(Exception e) {
        LogUtil.i(TAG, "---uploadImgFail===" + e.getMessage());
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                mPersonInfoLl.setVisibility(View.INVISIBLE);
                dismissProgressBar();
            }
        });
        showToast(e.getMessage(), Toast.LENGTH_SHORT);
    }

    @Override
    public void onFail(Exception e) {
        if (!TextUtils.isEmpty(e.getMessage())) {
            showToast(e.getMessage(), Toast.LENGTH_SHORT);
        }
        dismissProgressBar();
        LogUtil.i(TAG, "---onFail===" + e.getMessage());
    }

    @Override
    public void registSuccess(RegisterObjBean bean) {
        mSpHelper.putRegistInfo(bean);
        showToast("注册成功", 1);
        setResultAndFinish(REGIST_SUCCESS);
    }

    @Override
    public void getSecretSuccess(String sceret) {

    }

    @Override
    public void onFail(ResponseException e) {
        LogUtil.i(TAG, "---ResponseException===" + e.getMessage());
        if (!TextUtils.isEmpty(e.getMessage())) {
            showToast(e.getMessage(), 0);
        }
    }

    @Override
    public void loginSuccess(LoginObjBean bean) {
        mUserNotRegistered = false;
        mSpHelper.putLoginInfo(bean);
        showToast(getString(R.string.user_is_registered), 0);
        setResultAndFinish(REGIST_FAILED_IS_REGISTERED);
    }

    @Override
    public Context getViewContext() {
        return this;
    }

    @Override
    public void userNotRegistered() {
        mUserNotRegistered = true;
    }

    @Override
    public void reLogin() {

    }
}
